import { deleteSubject, insertOneSubject, lookSubject, lookSubjectAll, updateOneSubject } from '@/api/subject'

const getDefaultState = () => {
  return {
    subjectList: {},
  }
}

const state = getDefaultState()

const mutations = {
  SET_LIST: (state, value) => {
    state.subjectList = value
  },
}

const actions = {
  // 条件查询
  async lookSubjectAll({ commit, state }, subject) {
    return new Promise((resolve, reject) => {
      // 缓存
      if (state.subjectList.length > 0) {
        resolve(state.subjectList)
        return
      }
      lookSubjectAll(subject)
        .then((response) => {
          commit('SET_LIST', response)
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 条件查询
  async lookSubject({ state }, subject) {
    return new Promise((resolve, reject) => {
      lookSubject(subject)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 添加一条科目
  async insertOneSubject({ state }, subject) {
    return new Promise((resolve, reject) => {
      insertOneSubject(subject)
        .then((response) => {
          store.dispatch('subject/resetList')
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 修改科目
  async updateOneSubject({ state }, subject) {
    return new Promise((resolve, reject) => {
      updateOneSubject(subject)
        .then((response) => {
          store.dispatch('subject/resetList')
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 批量删除科目
  async deleteSubjects({ state }, ids) {
    return new Promise((resolve, reject) => {
      deleteSubject(ids)
        .then((response) => {
          store.dispatch('subject/resetList')
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 重置列表
  async resetList({ commit, state }) {
    // 置空
    if (state.routerList.length > 0) {
      commit('SET_LIST', [])
    }
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
